package com.gaoch.simweather.ui.place

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import com.gaoch.simweather.R
import com.gaoch.simweather.tools.showToast
import com.gaoch.simweather.ui.weather.WeatherActivity
import kotlinx.android.synthetic.main.fragment_place.*

class PlaceFragment:Fragment() {
    val viewModel by lazy { ViewModelProvider(this).get(PlaceViewModel::class.java) }
    private lateinit var adapter: PlaceAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_place,container,false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        if(viewModel.isPlaceSaved()){
            val location=viewModel.getSavedPlace()
            val intent= Intent(context, WeatherActivity::class.java).apply {
                putExtra("location",location.id)
                putExtra("cityName",location.name)
            }
            startActivity(intent)

        }

        val layoutManager=LinearLayoutManager(activity)
        fg_place_rv.layoutManager=layoutManager
        adapter= PlaceAdapter(this,viewModel.placeList)
        fg_place_rv.adapter=adapter
        fg_place_ed.addTextChangedListener {
            val content=it.toString()
            if(content.isNotEmpty()){
                viewModel.searchPlaces(content)
            }else{
                fg_place_rv.visibility=View.GONE
                fg_place_bgIv.visibility=View.VISIBLE
                viewModel.placeList.clear()
                adapter.notifyDataSetChanged()
            }
        }

        viewModel.placeLiveData.observe(this){
            val places=it.getOrNull()
            if(places!=null){
                fg_place_rv.visibility=View.VISIBLE
                fg_place_bgIv.visibility=View.GONE
                viewModel.placeList.clear()
                viewModel.placeList.addAll(places)
                adapter.notifyDataSetChanged()
            }else{
                "未能查询到任何地点".showToast()
                it.exceptionOrNull()?.printStackTrace()
            }
        }


    }
}